import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";

import { getSizeImage, formatDate, getPlaySong } from '@/utils/format-utils';
import {
    getSongDetailAction,
    changeSequenceAction,
    prevNextChangeSong,
    changeCurrentLyricIndexAction
} from "../store/actionCreators"

import {
    PlaybarWrapper,
    Control,
    PlayInfo,
    Operator
} from './style';

import { message } from 'antd';
import { NavLink } from 'react-router-dom';
import { Slider } from 'antd';
import CJXAppPlayList from "../app-player-panel";


let hide;//用于关闭歌词提示得，如果下一收歌曲没有歌词，就关闭歌词提示

export default memo(function CJXAppPlayerBar() {
    //1、state
    const [currentTime, setCurrentTime] = useState(0);//当前歌曲已经播放了多少时间 ms
    const [isPlaying, setIsPlaying] =  useState(false);//当前音乐是否在播放
    const [progress, setProgress] = useState(0);// 进度条 总的是 100
    const [isChanging, setIsChanging] = useState(false);//是否正在使用鼠标控制进度条发生变化
    const [showPanel, setShowPanel] = useState(false);

    
    //2、redux hook
    const { currentSong, sequence, playList, lyricList, currentLyricIndex } = useSelector(state => ({
        currentSong: state.getIn(["player", "currentSong"]),
        sequence: state.getIn(["player", "sequence"]),
        playList: state.getIn(["player", "playList"]),
        lyricList: state.getIn(["player", "lyricList"]),
        currentLyricIndex: state.getIn(["player", "currentLyricIndex"])
    }), shallowEqual);
    const dispatch = useDispatch();

    // console.log("播放顺序：", sequence);

    //3、other hook
    const audioRef = useRef();
    useEffect(() => {
        //发送http请求，获取歌曲
        dispatch(getSongDetailAction(167876));
        
    }, [dispatch]);
    useEffect(() => {
        // console.log("组件渲染：", currentSong.id);
        // console.log(!currentSong.id);
        audioRef.current.src = getPlaySong(currentSong.id);//第一次组件渲染 currentSong 是空定的
        //自动播放歌曲
        audioRef.current.play().then(res => {
            setIsPlaying(true);
        }).catch(err => {
            setIsPlaying(false);
        })
    }, [currentSong]);

    

    //4、other handle
    const picUrl = (currentSong.al && currentSong.al.picUrl) || "";
    const singerName = (currentSong.ar && currentSong.ar[0].name) || "未知歌手";
    const duration = currentSong.dt || 0;//歌曲的总时间  ms
    const showDuration = formatDate(duration, "mm:ss");//歌曲总时间格式化
    const showCurrentTime = formatDate(currentTime, "mm:ss");//当前歌曲播放的时间的格式化 
    // let hide;


    //5、other function
    //音乐播放时 触发的函数
    const timeUpdate = (e) => {
        let audioCurrentTime = parseInt(e.target.currentTime * 1000);//获取当前播放到到的时间 e.target.currentTime 是 s 
        // console.log(audioCurrentTime);
        if (!isChanging) {
            setCurrentTime(audioCurrentTime);
            // setProgress(currentTime / duration * 100);
            setProgress(audioCurrentTime / duration * 100);
        }

        //找到正在播放的那句歌词
        if (lyricList.length === 0 && hide) {
            //如果一下首歌曲没有歌词就关闭歌词提示
            hide();
            return;
        }
        let i = 0;
        for (; i < lyricList.length; i++) {
            if (audioCurrentTime < lyricList[i].time) {
                break;
            }
        }
        // console.log(lyricList[i-1]);
        if (currentLyricIndex !== (i -1)) {
            // console.log(i - 1);
            // console.log(lyricList[i-1]);
            dispatch(changeCurrentLyricIndexAction(i - 1));
            const content = lyricList[i-1] && lyricList[i-1].content;
            if (!content) return;
            hide = message.open({
                key: "lyric",
                content: content,
                duration: 0,
                className: "lyric-class"
            });
        }

    }
    //歌曲播放结束后 触发的函数
    const handleMusicEnded = () => {
        if (sequence === 2 || playList.length === 1) {
            //单曲循环
            audioRef.current.currentTime = 0;//将音频这是为 0 从零开始播放
            audioRef.current.play();//调用播放函数，

        } else {
            //顺序播放 或者 随机播放
            // if (playList.length == 1) {
            //     audioRef.current.currentTime = 0;//将音频这是为 0 从零开始播放
            //     audioRef.current.play();//调用播放函数
            // }
            dispatch(prevNextChangeSong(1));

        }
    }
    //切歌
    const changeMusic = useCallback((tag) => {
        // console.log("changeMusic");
        dispatch(prevNextChangeSong(tag));

    },[dispatch])

    const playMusic = useCallback(() => {
        isPlaying ? audioRef.current.pause(): audioRef.current.play();
        setIsPlaying(!isPlaying);
    }, [isPlaying]);
    //改变歌曲播放的顺序
    const changeSequence = useCallback(() => {
        let currentSequence = sequence + 1;
        if (currentSequence > 2) {
            currentSequence = 0;
        }
        // console.log();
        dispatch(changeSequenceAction(currentSequence));
    }, [sequence, dispatch]);

    //鼠标正在滑动 进度条时候触发函数
    const sliderChange = useCallback((value) => {
        const slideringTime = (value / 100 ) * duration;
        setCurrentTime(slideringTime);
        setIsChanging(true);
        setProgress(value);
        // console.log(value);
        //==>>必须加上这个 duration 依赖。第一次的时候 可能 duration 是 0, 不依赖 duration 的数 回调函数里面的 duration 就是第一次的值
    }, [duration]);
    //鼠标控制进度条滑动，松开鼠标(结束后)触发函数
    const sliderAfterChange = useCallback((value) => {
        // value 是进度条的 百分比 
        // console.log(audioRef);
        const slideringTime = (value / 100 ) * duration / 1000;
        audioRef.current.currentTime = slideringTime;// 让音乐从哪个位置播放 需要设置为 s
        //===>>需要设置当前音乐播放的时间，否则进度条会有一个会跳的过程
        setCurrentTime(slideringTime * 1000);
        setIsChanging(false);

        //松开鼠标，歌曲没有播放的话让它播放歌曲
        if (!isPlaying) {
            playMusic();
        }

    }, [duration, isPlaying, playMusic]);

    return (
        <PlaybarWrapper className="sprite_player">
            <div className="content wrap-v2">
                <Control isPlaying={isPlaying}>
                    <button className="sprite_player prev"
                        onClick={e => changeMusic(-1)}></button>
                    <button className="sprite_player play"
                        onClick={e => playMusic()}></button>
                    <button className="sprite_player next"
                        onClick={e => changeMusic(1)}></button>
                </Control>
                <PlayInfo>
                    <div className="image">
                        {/* <div>
                            <img src={getSizeImage(picUrl, 35)} alt="" />
                        </div> */}
                        <NavLink to={{
                                pathname: "/discover/player",
                                state: {id: currentSong.id},
                                search: "?id="+currentSong.id
                            }}>
                            <img src={getSizeImage(picUrl, 35)} alt="" />
                        </NavLink>
                    </div>
                    <div className="info">
                        <div className="song">
                            <span className="song-name">{currentSong.name}</span>
                            <a href="#/" className="singer-name">{singerName}</a>
                        </div>
                        <div className="progress">
                            <Slider defaultValue={30}
                                value={progress}
                                onChange={sliderChange}
                                onAfterChange={sliderAfterChange} />
                            <div className="time">
                                <span className="now-time">{showCurrentTime}</span>
                                <span className="divider">/</span>
                                <span className="duration">{showDuration}</span>
                            </div>
                        </div>
                    </div>
                </PlayInfo>
                <Operator sequence={sequence}>
                    <div className="left">
                        <button className="sprite_player btn favor"></button>
                        <button className="sprite_player btn share"></button>
                    </div>
                    <div className="right sprite_player">
                        <button className="sprite_player btn volume"></button>
                        <button className="sprite_player btn loop" onClick={e => changeSequence()}></button>
                        <button className="sprite_player btn playlist" onClick={e => setShowPanel(!showPanel)} >{ playList.length }</button>
                    </div>
                </Operator>
            </div>
            <audio ref={audioRef} 
                onTimeUpdate={e => timeUpdate(e)} 
                onEnded={e => handleMusicEnded()}/>
            {showPanel && <CJXAppPlayList />}
        </PlaybarWrapper>
    )
})